<!-- 产品中心和规格清单 表格组件-->
<template>
	<view>

		<uni-table stripe class="sticky-table">
			<uni-tr class="table-header header-row">
				<uni-th align="center" width="200">型号</uni-th>
				<!-- <uni-th align="center" width="150">商品主图</uni-th> -->
				<uni-th align="center" width="210">规格</uni-th>
				<uni-th align="center" width="100">工程图</uni-th>
				<!-- <uni-th align="center" width="80">对比</uni-th> -->
				<uni-th align="center" width="80">单价</uni-th>
				<uni-th align="center" width="100">发货日期</uni-th>
				<uni-th align="center" width="180">购物车</uni-th>
			</uni-tr>
		</uni-table>
		<scroll-view scroll-y="true" class="scrollable-body" :style="{height: scrollableBodyHeight}">
			<uni-table border stripe>
				<!-- <view> -->
				<template v-for="(item, index) in listData" :key="index" class="" style="overflow-y: auto;">
					<uni-tr class="data-row" v-if="item.price!=99999 && item.price != 999999">

						<uni-td width="200" @click="toggleExpand(index)">
							<uni-icons type="right" :class="['expand-icon',item.isExpanded?'iconRotate':'']"
								size="14"></uni-icons>
							<text class="model">{{ item.model }}</text>
						</uni-td>

						
						<uni-td align="center" width="210" class="itemSpec" :title="item.spec">{{ item.spec }}</uni-td>
						<uni-td align="center" width="100" class="scrollable-text">
							
							<text
								:class="['download-link','iconfont','icon-sheshisanweihua',item.zh_3d.url?'download-link1':'']"
								@click="download_3d(item.zh_3d,item)" title="商品3D文件"></text>
							<text :class="['download-link','iconfont','icon-pdf1',item.zh_pdf.url?'download-link1':'']"
								@click="download_pdf(item.zh_pdf,item)" title="商品pdf文件"></text>
						</uni-td>
						
						<uni-td align="center" width="80"><text
								class="popup-td-text">¥</text>{{ (item.price-0).toFixed(2) }}</uni-td>
						<uni-td align="center" width="100">{{ item.delivery_time }}</uni-td>
						<uni-td align="center" width="180">
							<view class="cart-group">
								<button class="cart-btn" :disabled="item.number <= 1"
									@click="decrease(index)">-</button>
								<input maxlength="4" type="number" v-model="item.number" :value="1" class="cart-input"
									@blur="handleCountChange(item, index)" />
								<button class="cart-btn" :disabled="item.number>=9999"
									@click="increase(index)">+</button>
								<button class="cart-add" @click="addToCart(index,$event)">
									<uni-icons type="plusempty" style="color: #FFF;" size="12"></uni-icons>
									购物车
								</button>
							</view>
							
							
							
						</uni-td>
					</uni-tr>
					
					<uni-tr class="data-row" v-else>
					
						<uni-td width="200" colspan="6">
							<view class="data-dingzhi">
								联系客服定制(0530-2216166)
							</view>
						</uni-td>
					
						
					</uni-tr>
					
					
					<uni-tr class="data-row" v-show="item.isExpanded?true:false">
						
						<uni-td colspan="7" class="detail-box">
							
							<view v-html="item.item"></view>
							
						</uni-td>
					</uni-tr>
				</template>
			</uni-table>
		</scroll-view>
		
	</view>
</template>

<script>
	import cartUtil from '../../common/cart.js';
	export default {
		name: "productForm",
		data() {
			return {
				listData: [],
				endPosition: { // 小球运动的终点
					endX: 1334,
					endY: 752
				},
				cartTotalCount: 0, // 购物车数量

			};
		},
		props: {
			scrollableBodyHeight: {
				type: String, // 数字类型
				required: false, // 必填项
				default: '532px' // 默认值
			},
			goods_id: { // 商品id
				type: String, // 数字类型
				required: false, // 必填项
				default: '' // 默认值
			},
			param: { // 详情页数据
				type: Object, // 数字类型
				required: false, // 必填项
				default: null // 默认值
			},
			menuToolData: {
				type: Object, // 数字类型
				required: false, // 必填项
				default: null // 默认值
			},
			sku: { // 商品信息
				type: Array, // 数字类型
				required: false, // 必填项
				default: null // 默认值
			},
		},
		mounted() {
			// this.listData = this.param.param
			this.listData = this.sku.sku
			
		},
		methods: {

			// 展开详细资料
			toggleExpand(index) {
				this.listData[index].isExpanded = !this.listData[index].isExpanded;
			},

			
			decrease(index) {
				
				if (this.listData[index].number > 1) {
					this.listData[index].number--;
				} else {
					this.listData[index].number = 1
				}
				
			},
			// 增加数量
			increase(index) {
				if (this.listData[index].number) {
					this.listData[index].number++;
				} else {
					this.listData[index].number = 2
				}
			},
			// 数量输入框改变
			handleCountChange(item, index) {
				console.log(item.number)
				const val = item.number;
				if (val && val > 0) {
					console.log('大于0')
					item.number = parseInt(val);
				} else {
					console.log(0)
					item.number = 1;
				}
			},
			// 加入购物车
			async addToCart(index, e) {

				if (!uni.getStorageSync('login-userinfo')._id) {
					uni.showToast({
						title: '请先登录',
						icon: 'none'
					});
					uni.navigateTo({
						url: '/pages/login/login'
					});
					
					return;
				} 

				// this.$refs.animation.startFromButton(e)
				let goods = this.listData[index];
				// uni.showLoading({
				// 	title: '处理中...'
				// });
				let defaultSpec = {
					...goods,
					model: goods.model, //模型
					specs: goods.spec, //规格
					price: goods.price, //价格
					// image: goods.image, //主图
					image: this.sku.goods_image[0], //主图
					number: goods.number ? goods.number : 1 // 数量
				};
				let detailsData = {
					goods_id: this.param._id || this.goods_id._id,
					goods_title: this.param.title,
					goods_image: this.param.images[0].url,
				};
				defaultSpec.serial_number = goods.serial_number; // 产品编号
				defaultSpec.total_price = defaultSpec.price * defaultSpec.number; // 计算总价
				defaultSpec.delivery_date = goods.delivery_time; // 发货周期

				const uid = uni.getStorageSync('login-userinfo')._id
				const totalCount = await cartUtil.addToCart({
					detailsData: detailsData,
					param: defaultSpec
				}, uid);
				
				this.cartTotalCount = totalCount.totalN;
				console.log('totalCount:::', totalCount.totalN)

				// 通知其他页面
				this.$emit('cartCountChange', totalCount.totalN,e);

			},
			download_img(arr, item) {

				if (!arr) {
					uni.showToast({
						title: '联系客服上传文件',
						icon: 'none'
					})
					return;
				}


				// 提取所有图片的url组成数组
				const urls = [arr]
				console.log(item)
				// 调用UniApp预览图片API
				uni.previewImage({
					current: 0, // 当前显示图片的索引
					urls: urls, // 需要预览的图片链接列表
					loop: true, // 是否可循环预览
					success: res => {
						console.log('预览图片成功', res);
					},
					fail: err => {
						console.error('预览图片失败', err);
					}
				});
			},
			download_3d(zh_3d, item) {
				console.log(item)
				console.log(zh_3d)
				if (!zh_3d.url) {
					uni.showToast({
						title: '联系客服上传文件',
						icon: 'none'
					})
					return;
				}

				let url = zh_3d.url;
				let title = zh_3d.title;
				const xhr = new XMLHttpRequest();
				xhr.open('GET', url, true);
				xhr.responseType = 'blob';

				// // 下载完成处理
				xhr.onload = function() {
					if (this.status === 200) {

						const blob = new Blob([this.response], {
							type: 'application/step'
						});
						url = URL.createObjectURL(blob);

						const a = document.createElement('a');
						a.href = url;
						a.download = title;
						document.body.appendChild(a);
						a.click();
						window.URL.revokeObjectURL(url);
						document.body.removeChild(a);
					} else {
						console.error('文件下载失败，状态码：', this.status);
						uni.showToast({
							title: '下载失败',
							icon: 'none'
						});
					}

					
				}
				xhr.onerror = function() {
					console.log('下载请求发生错误');
					uni.showToast({
						title: '下载出错',
						icon: 'none'
					});
				};
				// 发送请求
				xhr.send();
			},
			download_pdf(zh_pdf, item) {
				console.log(zh_pdf)
				console.log('item:', item)
				if (!zh_pdf.url) {
					uni.showToast({
						title: '联系客服上传文件',
						icon: 'none'
					})
					return;
				}
				let url = zh_pdf.url;
				let title = zh_pdf.title;
				

				const xhr = new XMLHttpRequest();
				xhr.open('GET', url, true);
				xhr.responseType = 'blob';

				// 下载完成处理
				xhr.onload = function() {
					if (this.status === 200) {
						// 创建blob对象
						const blob = new Blob([this.response]);

						// 创建下载链接
						const a = document.createElement('a');
						const url = window.URL.createObjectURL(blob);
						a.href = url;
						a.download = title;
						document.body.appendChild(a);
						a.click();
						window.URL.revokeObjectURL(url);
						document.body.removeChild(a);
					} else {
						console.error('文件下载失败，状态码：', this.status);
						uni.showToast({
							title: '下载失败',
							icon: 'none'
						});
					}

					
				}
				xhr.onerror = function() {
					console.log('下载请求发生错误');
					uni.showToast({
						title: '下载出错',
						icon: 'none'
					});
				};
				// 发送请求
				xhr.send();
			},
			arrayToString(arr) {
				if (!Array.isArray(arr)) {
					console.warn('输入不是数组，返回空字符串');
					return '';
				}
				return arr.map(item => {
					// 将元素转为字符串，然后直接去除所有\n（替换为空字符串）
					return String(item).replace(/\n/g, '');
				}).join(','); // 元素之间用逗号连接
			},
			positionDataFun(val) {
				this.endPosition.endX = val.left + 30
				this.endPosition.endY = val.top + 40
			},
		}
	}
</script>

<style scoped>
	.data-dingzhi{width:250px;height:35px;background:#d9001b;line-height:35px;text-align: center;color:#fff;border-radius: 17.5px;margin-left:calc((100% - 250px)/2);margin-top:20px;margin-bottom:20px;}
	.sticky-table {
		display: table;
		width: 100%;
		overflow-y: auto;
		margin-top: 5px;
		/* height: 300px; */
	}

	.sticky-table /deep/ .uni-table-loading {
		display: none;
	}

	.sticky-table /deep/ .uni-table {
		overflow-y: auto;
	}

	.table-header {
		/* background: #d9001b; */
		/* color: #333; */
	}

	.header-row {
		background: #efefef;
		/* color: #333; */
		position: sticky;
		top: 0;
		z-index: 1;
	}

	.model {
		/* color: #d9001b; */
		color: #000;
		font-weight: bold;
		padding-left: 28px;
	}

	.expand-icon {
		position: absolute;
		cursor: pointer;
		transition: all 0.3s ease;
		transform-origin: center;
		width: 26px;
		height: 26px;
		text-align: center;
		line-height: 26px;
	}

	.iconRotate {
		transform: rotate(-90deg);
	}

	.download-link {
		/* color: #ccc; */
		color: #ccc;
		/* text-decoration: underline; */
		font-size: 20px;
		padding: 0 5px;
	}

	.download-link1 {
		color: #d9001b;
		cursor: pointer;
	}

	.popup-checkbox /deep/ .uni-checkbox-input {
		width: 13px;
		height: 13px;
	}

	.popup-td-text {
		font-size: 12px;
	}

	.cart-group {
		display: flex;
		/* align-items: center; */
		/* justify-content: center; */
		max-width: 170px;
		margin: auto;
	}

	.cart-btn {

		width: 24px;
		height: 24px;
		line-height: 24px;
		text-align: center;
		padding: 0;
	}

	.cart-input {
		width: 40px;
		height: 20px;
		text-align: center;
		border: 1px solid #ddd;
		/* margin: 0 5px; */
	}

	.cart-add {
		background: #d9001b;
		color: white;
		border: none;
		padding: 0 5px;
		margin-left: 10px;
		font-size: 12px;
		line-height: 24px;

	}

	.detail-box {
		background: #f9f9f9;
		padding: 20px 40px;
		margin: 5px 0;
	}

	.detail-box /deep/ table {
		border: 1px #EBEEF5 solid;
		width: 100%;
	}

	.detail-box /deep/ td {
		border: 1px solid #EBEEF5;
	}

	.detail-box /deep/ td:nth-last-child(1) {
		border-right: 0px solid #EBEEF5;
	}

	.detail-box /deep/ td:nth-child(1) {
		border-left: 0px solid #EBEEF5;
	}

	/* .detail-box ::v-deep tr {
		border-bottom: 2px dashed #ff0000;
	} */

	.detail__title {
		font-size: 15px;
		font-weight: bold;
		margin-bottom: 20px;
	}

	.detail-table {
		width: 100%;
		border-collapse: collapse;
	}

	.detail-table th,
	.detail-table td {
		border: 1px solid #ddd;
		padding: 5px 10px;
		text-align: left;
		font-weight: 400;
	}

	.uni-table-th {
		color: #333;
	}

	.data-row {
		/* display: flex; */
	}


	.commodity-view {
		width: 100%;
		height: 100%;
		display: flex;
		background-color: #f9f9f9;
		padding: 20px;
		box-sizing: border-box;
	}

	.commodity-image {
		width: 80px;
		height: 80px;
		/* margin: auto; */
		cursor: pointer;
	}

	.data-row /deep/ .model {
		cursor: pointer;
	}

	.data-row /deep/ .itemSpec {
		max-width: 200px;
		white-space: nowrap;
		/* 禁止文本换行 */
		overflow: hidden;
		/* 隐藏超出容器的内容 */
		text-overflow: ellipsis;
		/* 超出部分显示省略号 */
	}

	.scrollable-text text {
		line-height: 25px;
	}

	.data-width {
		width: 50%;
	}

	.data-width text {
		/* width: 30%; */
		display: inline-block;
	}

	.data-width text:last-child {
		font-weight: 400;
		font-size: 14px;
		/* width: 70%; */
		padding: 0 10px 0 20px;
	}

	.table--stripe .uni-table-tr:nth-child(2n+3) {
		background-color: #FFF;
	}
</style>